package com.atguigu.tingshu.search.executor;

import com.atguigu.tingshu.common.constant.RedisConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * <a href="https://www.shallowrecall.top/">Recall`Blog</a></br>
 * <a href="https://github.com/ShallowRecall">GitHub</a>
 *
 * @author Recall
 * @createTime 2025/03/25 19:49
 **/
public class ExpireThreadExecutor {
    private Long ttl;
    private TimeUnit timeUnit;

    private StringRedisTemplate stringRedisTemplate;
    private Long taskId;
    static ScheduledExecutorService scheduledExecutorService;
    static ScheduledFuture<?> scheduledFuture = null;
   Logger logger = LoggerFactory.getLogger(ExpireThreadExecutor.class);

    static {
        scheduledExecutorService = Executors.newScheduledThreadPool(2);

    }

    public ExpireThreadExecutor(StringRedisTemplate stringRedisTemplate, Long taskId) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.taskId = taskId;
    }

    /**
     * 定义一个续期方法
     */
    public void renewal(Long ttl, TimeUnit timeUnit) {

        scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                logger.info("续期任务开始执行......");
                // 续期
                stringRedisTemplate.expire(RedisConstant.ALBUM_LOCK_SUFFIX + taskId, ttl, timeUnit);
            }
        }, ttl / 3, ttl / 3, TimeUnit.SECONDS);
    }

    /**
     * 中断续期任务的方法
     */
    public Boolean cancelRenewal() {
        //取消给线程池的任务
        logger.info("取消续期任务......");
        return scheduledFuture.cancel(true);
    }

}
